<template>
  <div class="budget-sheet-form">
    <!-- 顶部卡片 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="title">{{ title }}</div>
          <div class="buttons">
            <el-button :icon="Back" @click="goBack">返回</el-button>
            <el-button type="success" @click="handlePreviewBudgetSheet">预览预算单</el-button>
            <el-button v-if="!isViewMode" type="primary" :icon="Check" :loading="submitLoading" @click="submitForm">提交</el-button>
          </div>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="right"
        :disabled="isViewMode"
      >
        <!-- 基本信息卡片 -->
        <el-card class="base-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="项目名称" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择项目" clearable filterable class="full-width" @change="handleProjectChange">
                  <el-option 
                    v-for="item in projectList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="customerId">
                <template #label>
                  <span>客户名称</span>
                  <el-tooltip content="选择项目时会自动填充" placement="top">
                    <el-icon style="margin-left: 4px; color: #909399;"><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
                <el-select v-model="form.customerId" placeholder="请选择客户" clearable filterable class="full-width" disabled>
                  <el-option 
                    v-for="item in customerList" 
                    :key="item.id" 
                    :label="item.companyName" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="personId">
                <template #label>
                  <span>业务员</span>
                  <el-tooltip content="选择项目时会自动填充" placement="top">
                    <el-icon style="margin-left: 4px; color: #909399;"><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
                <el-select v-model="form.personId" placeholder="请选择业务员" clearable filterable class="full-width" disabled>
                  <el-option 
                    v-for="item in personList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="目标金额" prop="targetAmount">
                <el-input-number v-model="form.targetAmount" :precision="2" :step="1000" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售订单类型" prop="saleType">
                <el-select v-model="form.saleType" placeholder="请选择销售订单类型" clearable filterable class="full-width">
                  <el-option 
                    v-for="item in saleTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
  
            <el-col :span="8">
              <el-form-item prop="integratedPlanningType">
                <template #label>
                  <span>集成规划类型</span>
                  <el-tooltip content="选择项目时会自动填充" placement="top">
                    <el-icon style="margin-left: 4px; color: #909399;"><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
                <el-select v-model="form.integratedPlanningType" placeholder="请选择集成规划类型" clearable filterable class="full-width" disabled>
                  <el-option 
                    v-for="item in planningTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item prop="orderType">
                <template #label>
                  <span>订单类型1</span>
                  <el-tooltip content="选择项目时会自动填充" placement="top">
                    <el-icon style="margin-left: 4px; color: #909399;"><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
                <el-select v-model="form.orderType" placeholder="请选择订单类型1" clearable filterable class="full-width" disabled>
                  <el-option 
                    v-for="item in orderTypeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="orderType2">
                <template #label>
                  <span>订单类型2</span>
                  <el-tooltip content="选择项目时会自动填充" placement="top">
                    <el-icon style="margin-left: 4px; color: #909399;"><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
                <el-select v-model="form.orderType2" placeholder="请选择订单类型2" clearable filterable class="full-width" disabled>
                  <el-option 
                    v-for="item in orderType2Options" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
  
            <el-col :span="8">
              <el-form-item label="质保期(年)" prop="warrantyPeriodYear">
                <el-select v-model="form.warrantyPeriodYear" placeholder="请选择订单类型2" clearable filterable class="full-width">
                  <el-option 
                    v-for="item in warrantyPeriodYearOptions" 
                    :key="item.dictValue" 
                    :label="item.dictLabel" 
                    :value="item.dictValue" 
                  />
                </el-select>              
                </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="项目动画视频" prop="projectAnimationVideo">
                <el-select v-model="form.projectAnimationVideo" placeholder="请选择是否有项目动画视频" clearable filterable class="full-width">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 实时预算预览区域 -->
        <el-card class="preview-info-card" shadow="never" style="margin-bottom: 20px;">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>实时预算预览</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-alert
                v-if="previewData.grossMargin !== undefined && previewData.grossMargin !== null"
                :title="`毛利率：${(previewData.grossMargin * 100).toFixed(2)}%`"
                type="success"
                show-icon
              />
            </el-col>
            <el-col :span="8">
              <el-alert
                v-if="previewData.totalWeight !== undefined && previewData.totalWeight !== null"
                :title="`总重量：${previewData.totalWeight.toFixed(2)}kg`"
                type="info"
                show-icon
              />
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 费用信息卡片 -->
        <el-card class="fee-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>费用信息</span>
            </div>
          </template>
          
          <!-- 其他费用列表 -->
          <el-form-item label="其他费用" prop="otherExpenses">
            <div class="other-expenses-container">
              <div v-for="(item, index) in otherExpensesList" :key="index" class="other-expense-item">
                <el-row :gutter="10" align="middle">
                  <el-col :span="8">
                    <el-input-number 
                      v-model="item.amount" 
                      :precision="2" 
                      :step="100" 
                      :min="0" 
                      placeholder="费用金额"
                      class="full-width"
                      @change="calculateTotalOtherExpenses"
                    />
                  </el-col>
                  <el-col :span="12">
                    <el-input 
                      v-model="item.remark" 
                      placeholder="费用说明/备注"
                      class="full-width"
                    />
                  </el-col>
                  <el-col :span="4">
                    <el-button 
                      type="danger" 
                      size="small" 
                      :icon="Delete" 
                      @click="removeOtherExpense(index)"
                      :disabled="otherExpensesList.length === 1"
                    />
                    <el-button 
                      v-if="index === otherExpensesList.length - 1" 
                      type="primary" 
                      size="small" 
                      :icon="Plus" 
                      @click="addOtherExpense"
                    />
                  </el-col>
                </el-row>
              </div>
              <div class="other-expenses-total">
                <span>其他费用合计：{{ totalOtherExpenses.toFixed(2) }} 元</span>
              </div>
            </div>
          </el-form-item>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="非标颜色费" prop="nonStandardColorFee">
                <el-input-number v-model="form.nonStandardColorFee" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="urgentFee">
                <template #label>
                  <span>加急费</span>
                  <el-tooltip :content="getUrgentFeeTipText()" placement="top">
                    <el-icon style="margin-left: 4px; color: #f56c6c;"><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
                <el-input-number v-model="form.urgentFee" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营销费用" prop="marketingExpensesFee">
                <el-input-number v-model="form.marketingExpensesFee" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
      
            <el-col :span="8">
              <el-form-item label="营销费用" prop="marketingExpenses">
                <el-select v-model="form.marketingExpenses" placeholder="请选择营销费用" clearable filterable class="full-width">
                  <el-option 
                    v-for="item in marketingExpensesOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>              
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优惠折扣(%)" prop="discountRate" v-permission="['sys:bs:zk']">
                <el-input-number v-model="form.discountRate" :precision="2" :step="1" :min="0" :max="100" v-permission="['sys:bs:zk']" class="full-width" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="结构件运输费" prop="transportationCostStructuralComponents">
                <el-input-number v-model="form.transportationCostStructuralComponents" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结构件安装费" prop="installationFeeStructuralComponents">
                <el-input-number v-model="form.installationFeeStructuralComponents" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备运输费" prop="deviceTransportationCost">
                <el-input-number v-model="form.deviceTransportationCost" :precision="2" :step="100" :min="0" class="full-width" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="结构件运输费备注" prop="transportationCostStructuralComponentsRemark">
                <el-input v-model="form.transportationCostStructuralComponentsRemark" placeholder="请输入结构件运输费备注" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结构件安装费备注" prop="installationFeeStructuralComponentsRemark">
                <el-input v-model="form.installationFeeStructuralComponentsRemark" placeholder="请输入结构件安装费备注" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备运输费备注" prop="deviceTransportationCostRemark">
                <el-input v-model="form.deviceTransportationCostRemark" placeholder="请输入设备运输费备注" clearable />
              </el-form-item>
            </el-col>
          </el-row>

        </el-card>
        
        <!-- 付款信息卡片 -->
        <el-card class="payment-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>付款信息</span>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="prepaymentRatio">
                <template #label>
                  <span>预付款比例%</span>
                  <el-tooltip content="根据其他比例自动计算：100% - 到货款比例% - 安装验收款比例% - 质保金比例%" placement="top">
                    <el-icon style="margin-left: 4px; color: #909399;"><InfoFilled /></el-icon>
                  </el-tooltip>
                </template>
                <el-input-number v-model="form.prepaymentRatio" :precision="2" :step="1" :min="0" disabled class="full-width" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 到货款信息列表 -->
          <el-form-item label="到货金额信息">
            <div class="payment-info-container">
              <!-- 列标题 -->
              <div class="payment-info-header">
                <el-row :gutter="10" align="middle">
                  <el-col :span="10">
                    <span class="column-header">到货款金额比例%</span>
                  </el-col>
                  <el-col :span="10">
                    <span class="column-header">付款周期(天)</span>
                  </el-col>
                  <el-col :span="4">
                    <span class="column-header">操作</span>
                  </el-col>
                </el-row>
              </div>
              <div v-for="(item, index) in deliveryPaymentList" :key="index" class="payment-info-item">
                <el-row :gutter="10" align="middle">

                  <el-col :span="10">
                    <el-input-number 
                      v-model="item.ratio" 
                      :precision="2" 
                      :step="1" 
                      :min="0" 
                      :max="100"
                      placeholder="到货款金额比例%"
                      class="full-width"
                      @change="calculatePaymentRatios"
                    />
                  </el-col>
                  <el-col :span="10">
                    <el-input-number 
                      v-model="item.cycle" 
                      :min="0" 
                      :max="365"
                      placeholder="付款周期(天)"
                      class="full-width"
                    />
                  </el-col>
                  <el-col :span="4">
                    <el-button 
                      type="danger" 
                      size="small" 
                      :icon="Delete" 
                      @click="removeDeliveryPayment(index)"
                      :disabled="deliveryPaymentList.length === 1"
                    />
                    <el-button 
                      v-if="index === deliveryPaymentList.length - 1" 
                      type="primary" 
                      size="small" 
                      :icon="Plus" 
                      @click="addDeliveryPayment"
                    />
                  </el-col>
                </el-row>
              </div>
              <div class="payment-info-total">
                <span>到货款比例合计：{{ totalDeliveryPaymentRatio.toFixed(2) }}%</span>
                <span style="margin-left: 20px;">付款周期合计：{{ calculateTotalCycle(deliveryPaymentList) }}天</span>
              </div>
            </div>
          </el-form-item>
          
          <!-- 安装验收款信息列表 -->
          <el-form-item label="安装验收款信息">
            <div class="payment-info-container">
              <!-- 列标题 -->
              <div class="payment-info-header">
                <el-row :gutter="10" align="middle">
                  <el-col :span="10">
                    <span class="column-header">安装验收款比例%</span>
                  </el-col>
                  <el-col :span="10">
                    <span class="column-header">付款周期(天)</span>
                  </el-col>
                  <el-col :span="4">
                    <span class="column-header">操作</span>
                  </el-col>
                </el-row>
              </div>
              <div v-for="(item, index) in installationPaymentList" :key="index" class="payment-info-item">
                <el-row :gutter="10" align="middle">
                  <el-col :span="10">
                    <el-input-number 
                      v-model="item.ratio" 
                      :precision="2" 
                      :step="1" 
                      :min="0" 
                      :max="100"
                      placeholder="安装验收款比例%"
                      class="full-width"
                      @change="calculatePaymentRatios"
                    />
                  </el-col>
                  <el-col :span="10">
                    <el-input-number 
                      v-model="item.cycle" 
                      :min="0" 
                      :max="365"
                      placeholder="付款周期(天)"
                      class="full-width"
                    />
                  </el-col>
                  <el-col :span="4">
                    <el-button 
                      type="danger" 
                      size="small" 
                      :icon="Delete" 
                      @click="removeInstallationPayment(index)"
                      :disabled="installationPaymentList.length === 1"
                    />
                    <el-button 
                      v-if="index === installationPaymentList.length - 1" 
                      type="primary" 
                      size="small" 
                      :icon="Plus" 
                      @click="addInstallationPayment"
                    />
                  </el-col>
                </el-row>
              </div>
              <div class="payment-info-total">
                <span>安装验收款比例合计：{{ totalInstallationPaymentRatio.toFixed(2) }}%</span>
                <span style="margin-left: 20px;">付款周期合计：{{ calculateTotalCycle(installationPaymentList) }}天</span>
              </div>
            </div>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="质保金比例%" prop="warrantyMoney">
                <el-input-number v-model="form.warrantyMoney" :precision="2" :step="1" :min="0" class="full-width" @change="calculatePrepaymentRatio" />
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item label="质保期(月)" prop="warrantyPeriodMonth">
                <el-input-number v-model="form.warrantyPeriodMonth" :min="0" :max="12" class="full-width" />
              </el-form-item>
            </el-col>

          </el-row>

          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="承兑金额" prop="acceptanceMoney">
                <el-input-number v-model="form.acceptanceMoney" :precision="2" :step="1" :min="0"  class="full-width" />

              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="承兑时间(月)" prop="acceptanceTime">
                <el-input-number v-model="form.acceptanceTime" :precision="2" :step="1" :min="0"  class="full-width" />
              </el-form-item>
            </el-col>

          </el-row>
        </el-card>
      </el-form>
    </el-card>

    <!-- 预算单预览弹窗 -->
    <el-dialog
      v-model="budgetDialog.visible"
      :title="budgetDialog.title"
      :width="budgetDialog.width"
      :before-close="handleCloseBudgetDialog">
      <BudgetSheetPreview 
        :budget-data="currentBudgetSheet" 
        :warranty-period-year-options="warrantyPeriodYearOptions"
        :delivery-payment-details="deliveryPaymentList"
        :installation-payment-details="installationPaymentList"
        ref="budgetPreviewRef">
        <template #footer>
          <div class="print-area">
            <el-button type="primary" @click="printBudgetSheet" class="print-button">打印预算单</el-button>
          </div>
        </template>
      </BudgetSheetPreview>
      
             <template #footer>
         <el-button @click="handleCloseBudgetDialog">取消</el-button>
         <el-button type="primary" @click="printBudgetSheet">打印</el-button>
         <el-button v-if="currentBudgetSheet.id" type="success" @click="saveBudgetSheet">保存</el-button>
         <el-button v-if="!currentBudgetSheet.id" type="warning" disabled>保存（需先提交预算单）</el-button>
       </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { 
  getBudgetSheetDetailApi, 
  addBudgetSheetApi, 
  updateBudgetSheetApi,
  getBudgetSheetDetailAllApi,
  getBudgetSheetDetailPreviewApi,
  saveHistoricalBudgetSheetApi 
} from '@/api/budgetSheet/index'
import type { BudgetSheet, BudgetSheetCreateDTO, BudgetSheetUpdateDTO } from '@/api/budgetSheet/type'
import { Check, Back, Document, InfoFilled, Plus, Delete } from '@element-plus/icons-vue'
import { getListApi as getDictListApi } from "@/api/sysDictData"
import { SysDictData } from "@/api/sysDictData/type"
import { getSimpleProject, getProjectDocumentApi } from "@/api/project"
import { getSimpleCustomer } from "@/api/companyCustomer"
import { getSimpleUser } from "@/api/user"
import { debounce } from 'lodash-es'
import BudgetSheetPreview from '@/components/budgetSheet/BudgetSheetPreview.vue'

// 定义props接收路由传递的display参数
const props = defineProps({
  display: {
    type: String,
    default: 'false'
  }
})

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const id = computed(() => route.params.id ? Number(route.params.id) : undefined)
const title = computed(() => {
  if (isViewMode.value) {
    return '查看预算单'
  } else if (id.value) {
    return '编辑预算单'
  } else {
    return '新增预算单'
  }
})

// 是否为查看模式
const isViewMode = computed(() => route.query.display === 'true' || props.display === 'true')

// 项目列表
const projectList = ref<any[]>([])
// 客户列表
const customerList = ref<any[]>([])
// 业务员列表
const personList = ref<any[]>([])
// 销售订单类型选项
const saleTypeOptions = ref<SysDictData[]>([])
// 集成规划类型选项
const planningTypeOptions = ref<SysDictData[]>([])
// 订单类型1选项
const orderTypeOptions = ref<SysDictData[]>([])
// 订单类型2选项
const orderType2Options = ref<SysDictData[]>([])
// 质保期(年)选项
const warrantyPeriodYearOptions = ref<SysDictData[]>([])

// 根据dictValue获取dictLabel
const getWarrantyPeriodYearLabel = (value: string | number | undefined) => {
  const found = warrantyPeriodYearOptions.value.find(item => String(item.dictValue) === String(value))
  return found ? found.dictLabel : (value ?? '')
}
// 营销费用选项
const marketingExpensesOptions = ref<SysDictData[]>([])
// 加急费提示选项
const urgentFeeTipOptions = ref<SysDictData[]>([])

// 其他费用列表
const otherExpensesList = ref<Array<{amount: number, remark: string}>>([
  { amount: 0, remark: '' }
])

// 其他费用合计
const totalOtherExpenses = computed(() => {
  return otherExpensesList.value.reduce((total, item) => total + (item.amount || 0), 0)
})

// 到货款信息列表
const deliveryPaymentList = ref<Array<{ratio: number, cycle: number}>>([
  { ratio: 0, cycle: 0 }
])

// 安装验收款信息列表
const installationPaymentList = ref<Array<{ratio: number, cycle: number}>>([
  { ratio: 0, cycle: 0 }
])

// 到货款合计比例
const totalDeliveryPaymentRatio = computed(() => {
  return deliveryPaymentList.value.reduce((total, item) => total + (item.ratio || 0), 0)
})

// 安装验收款合计比例
const totalInstallationPaymentRatio = computed(() => {
  return installationPaymentList.value.reduce((total, item) => total + (item.ratio || 0), 0)
})

// 打印预算单相关
const budgetDialog = reactive({
  visible: false,
  title: '',
  width: '900px'
})

// 当前选中的预算单数据
const currentBudgetSheet = ref<BudgetSheet & {
  integratedPlanningType?: string;
  productCostExpenses?: number;
  productSalesAmount?: number;
  productPackagingExpenses?: number;
  productTransportExpenses?: number;
  shelfInstallationExpenses?: number;
  equipmentInstallationExpenses?: number;
  electricControlInstallationExpenses?: number;
  electricControlDebugExpenses?: number;
  softwareDebugExpenses?: number;
  projectManagementExpenses?: number;
  operationManagementExpenses?: number;
  warrantyPeriod?: number;
  otherExpenses?: number;
  marketingExpenses?: string;
  financialCost?: number;
  salesCommission?: number;
  total?: number;
  marketingExpensesPrice?: number;
  proportionReceivedPayment?: number;
  paymentCycle?: number;
  proportionReceivedPaymentAmount?: number;
  installationAcceptancePayment?: number;
  paymentCycle2?: number;
  installationAcceptancePaymentRatio?: number;
  warrantyCost?: number;
  warrantyPeriodMonth?: number;
  warrantyMoney?: number;
  acceptanceTime?: number | string;
  acceptanceMoney?: number | string;
  acceptanceMoneyCost?: number;
  salesCommissionAmount?: number;
  salesCommissionAmountRatio?: number;
  preSalesPlanningCommission?: number;
  preSalesPlanningCommissionRatio?: number;
  projectAnimationCommission?: number;
  projectAnimationCommissionRatio?: number;
  nonStandardColorFee?: number;
  urgentFee?: number;
  discountRate?: number;
  productCostDiscountFee?: number;
}>({})

// 表单数据
const form = reactive<BudgetSheet>({
  projectId: undefined,
  customerId: undefined,
  personId: undefined,
  targetAmount: undefined,
  grossMargin: undefined,
  saleType: undefined,
  integratedPlanningType: undefined,
  projectAnimationVideo: undefined,
  orderType: undefined,
  orderType2: undefined,
  warrantyPeriodYear: undefined,
  otherExpenses: undefined,
  nonStandardColorFee: undefined,
  marketingExpensesFee: undefined,
  urgentFee: undefined,
  discountRate: 100, // 默认不打折
  marketingExpenses: undefined,
  transportationCostStructuralComponents: undefined,
  installationFeeStructuralComponents: undefined,
  deviceTransportationCost: undefined,
  transportationCostStructuralComponentsRemark: undefined,
  installationFeeStructuralComponentsRemark: undefined,
  deviceTransportationCostRemark: undefined,
  paymentCycle: undefined,
  proportionReceivedPaymentAmount: undefined,
  paymentCycle2: undefined,
  installationAcceptancePaymentRatio: undefined,
  warrantyPeriodMonth: undefined,
  warrantyMoney: undefined,
  acceptanceTime: undefined,
  acceptanceMoney: undefined,
  productCostDiscountFee: undefined, // 产品成本优惠费用
  prepaymentRatio: undefined,
})

// 表单校验规则
const rules = reactive<FormRules>({
  projectId: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ],
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  personId: [
    { required: true, message: '请选择业务员', trigger: 'change' }
  ],
  targetAmount: [
    { required: true, message: '请输入目标金额', trigger: 'blur' }
  ],
  saleType: [
    { required: true, message: '请选择销售订单类型', trigger: 'change' }
  ],
  integratedPlanningType: [
    { required: true, message: '请选择集成规划类型', trigger: 'change' }
  ],
  orderType: [
    { required: true, message: '请选择订单类型1', trigger: 'change' }
  ],
  orderType2: [
    { required: true, message: '请选择订单类型2', trigger: 'change' }
  ],
  warrantyPeriodYear: [
    { required: true, message: '请选择质保期(年)', trigger: 'change' }
  ],
  projectAnimationVideo: [
    { required: true, message: '请选择项目动画视频', trigger: 'change' }
  ],
  otherExpenses: [
    { required: true, message: '请输入其他费用', trigger: 'blur' }
  ],
  nonStandardColorFee: [
    { required: true, message: '请输入非标颜色费', trigger: 'blur' }
  ],
  urgentFee: [
    { required: true, message: '请输入加急费', trigger: 'blur' }
  ],
  discountRate: [
    { required: true, message: '请输入优惠折扣', trigger: 'blur' }
  ],
  marketingExpenses: [
    { required: true, message: '请选择营销费用', trigger: 'change' }
  ],
  transportationCostStructuralComponents: [
    { required: true, message: '请输入结构件运输费', trigger: 'blur' }
  ],
  installationFeeStructuralComponents: [
    { required: true, message: '请输入结构件安装费', trigger: 'blur' }
  ],
  deviceTransportationCost: [
    { required: true, message: '请输入设备运输费', trigger: 'blur' }
  ],
  // 移除原有单字段验证，改为在提交时检查列表数据
  warrantyPeriodMonth: [
    { required: true, message: '请输入质保期(月)', trigger: 'blur' }
  ],
  warrantyMoney: [
    { required: true, message: '请输入质保金比例', trigger: 'blur' }
  ],
  acceptanceTime: [
    { required: true, message: '请输入承兑时间(月)', trigger: 'blur' }
  ],
  acceptanceMoney: [
    { required: true, message: '请输入承兑金额', trigger: 'blur' }
  ],
  transportationCostStructuralComponentsRemark: [
    { required: true, message: '请输入结构件运输费备注', trigger: 'blur' }
  ],
  installationFeeStructuralComponentsRemark: [
    { required: true, message: '请输入结构件安装费备注', trigger: 'blur' }
  ],
  deviceTransportationCostRemark: [
    { required: true, message: '请输入设备运输费备注', trigger: 'blur' }
  ]
  // 移除prepaymentRatio的校验规则，因为现在是自动计算的
})

// 获取项目列表
const getProjectOptions = async () => {
  try {
    const res = await getSimpleProject()
    projectList.value = res.data || []
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

// 处理项目选择变化
const handleProjectChange = async (projectId: number | undefined) => {
  if (projectId) {
    try {
      // 获取项目详情以确保信息完整
      const res = await getProjectDocumentApi(projectId)
      const projectDetail = res.data
      
      if (projectDetail) {
        // 自动填充关联字段
        form.customerId = projectDetail.customerId
        form.personId = projectDetail.person
        form.integratedPlanningType = projectDetail.integratedPlanningType
        form.orderType = projectDetail.orderType
        form.orderType2 = projectDetail.orderType2
       
      }
    } catch (error) {
      console.error('获取项目详情失败', error)
      ElMessage.warning('获取项目详情失败，请手动选择相关信息')
    }
  } else {
    // 如果清空项目选择，也清空关联字段
    form.customerId = undefined
    form.personId = undefined
    form.integratedPlanningType = undefined
    form.orderType = undefined
    form.orderType2 = undefined
  }
}

// 获取客户列表
const getCustomerOptions = async () => {
  try {
    const res = await getSimpleCustomer()
    customerList.value = res.data || []
  } catch (error) {
    console.error('获取客户列表失败', error)
  }
}

// 获取业务员列表
const getPersonOptions = async () => {
  try {
    const res = await getSimpleUser()
    personList.value = res.data || []
  } catch (error) {
    console.error('获取业务员列表失败', error)
  }
}

// 获取字典项
const getDictOptions = async (dictType: string) => {
  try {
    const res = await getDictListApi({ 
      dictType,
      page: 1,
      limit: 1000
    })
    return res.data || []
  } catch (error) {
    console.error(`获取字典${dictType}失败`, error)
    return []
  }
}


// 获取销售订单类型选项
const getSaleTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'saleType',
        dictLabel: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      saleTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取销售订单类型选项失败:', error)
  }
}

// 获取集成规划类型选项
const getPlanningTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'integratedPlanningType',
        dictLabel: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      planningTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取订单类型1选项
const getOrderTypeOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'orderType',
        dictLabel: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      orderTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取订单类型2选项
const getOrderType2Options = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'orderType',
        dictLabel: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      orderType2Options.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}
const getWarrantyPeriodYearOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'warrantyPeriodYear',
        dictLabel: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      warrantyPeriodYearOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}
// 获取营销费用选项
const getMarketingExpensesOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'marketingExpenses',
        dictLabel: "",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      marketingExpensesOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取加急费提示选项
const getUrgentFeeTipOptions = async () => {
  try {
    const res = await getDictListApi({
        dictType: 'budgetSheetTip',
        dictLabel: "urgentFeeTip",
        status: undefined,
        page: 0,
        limit: 100
    })
    if (res && res.data) {
      urgentFeeTipOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取加急费提示失败:', error)
  }
}

// 获取加急费提示文本
const getUrgentFeeTipText = () => {
  if (urgentFeeTipOptions.value.length > 0) {
    return urgentFeeTipOptions.value[0].dictValue || '加急费说明'
  }
  return '加急费说明'
}

// 计算预付款比例
const calculatePrepaymentRatio = () => {
  const receivedRatio = totalDeliveryPaymentRatio.value || 0
  const installationRatio = totalInstallationPaymentRatio.value || 0
  const warrantyRatio = form.warrantyMoney || 0
  
  // 预付款比例 = 100 - 到货款比例 - 安装验收款比例 - 质保金比例
  form.prepaymentRatio = Math.max(0, 100 - receivedRatio - installationRatio - warrantyRatio)
}

// 计算付款周期总和
const calculateTotalCycle = (paymentList: Array<{ratio: number, cycle: number}>) => {
  const validItems = paymentList.filter(item => item.ratio > 0)
  return validItems.reduce((sum, item) => sum + item.cycle, 0)
}

// 计算付款比例（统一方法）
const calculatePaymentRatios = () => {
  // 同步到表单字段（用于后端兼容）
  form.proportionReceivedPaymentAmount = totalDeliveryPaymentRatio.value
  form.installationAcceptancePaymentRatio = totalInstallationPaymentRatio.value
  
  // 计算付款周期总和
  form.paymentCycle = calculateTotalCycle(deliveryPaymentList.value)
  form.paymentCycle2 = calculateTotalCycle(installationPaymentList.value)
  
  // 计算预付款比例
  calculatePrepaymentRatio()
}

// 其他费用相关方法
const addOtherExpense = () => {
  otherExpensesList.value.push({ amount: 0, remark: '' })
}

const removeOtherExpense = (index: number) => {
  if (otherExpensesList.value.length > 1) {
    otherExpensesList.value.splice(index, 1)
    calculateTotalOtherExpenses()
  }
}

const calculateTotalOtherExpenses = () => {
  // 计算总费用并更新form.otherExpenses
  form.otherExpenses = totalOtherExpenses.value
}

// 到货款信息相关方法
const addDeliveryPayment = () => {
  deliveryPaymentList.value.push({ ratio: 0, cycle: 0 })
}

const removeDeliveryPayment = (index: number) => {
  if (deliveryPaymentList.value.length > 1) {
    deliveryPaymentList.value.splice(index, 1)
    calculatePaymentRatios()
  }
}

// 安装验收款信息相关方法
const addInstallationPayment = () => {
  installationPaymentList.value.push({ ratio: 0, cycle: 0 })
}

const removeInstallationPayment = (index: number) => {
  if (installationPaymentList.value.length > 1) {
    installationPaymentList.value.splice(index, 1)
    calculatePaymentRatios()
  }
}

// 获取预算单详情
const getBudgetSheetDetail = async () => {
  try {
    const res = await getBudgetSheetDetailApi(id.value as number)
    Object.assign(form, res.data)
    
    // 处理其他费用数据回显
    if (res.data.otherExpensesDetail) {
      try {
        // 如果有详细的其他费用数据，解析为列表
        const detailData = JSON.parse(res.data.otherExpensesDetail)
        if (Array.isArray(detailData) && detailData.length > 0) {
          otherExpensesList.value = detailData
        }
      } catch (e) {
        // 如果解析失败，保持默认结构，但设置总金额
        if (res.data.otherExpenses) {
          otherExpensesList.value = [{ amount: res.data.otherExpenses, remark: '其他费用' }]
        }
      }
    } else if (res.data.otherExpenses) {
      // 如果没有详细数据但有总金额，设置为单项
      otherExpensesList.value = [{ amount: res.data.otherExpenses, remark: '其他费用' }]
    }
    
    // 处理到货款信息数据回显
    if (res.data.deliveryPaymentDetail) {
      try {
        const deliveryData = JSON.parse(res.data.deliveryPaymentDetail)
        if (Array.isArray(deliveryData) && deliveryData.length > 0) {
          deliveryPaymentList.value = deliveryData
        }
      } catch (e) {
        // 如果解析失败，使用原有字段数据
        if (res.data.proportionReceivedPaymentAmount || res.data.paymentCycle) {
          deliveryPaymentList.value = [{
            ratio: res.data.proportionReceivedPaymentAmount || 0,
            cycle: res.data.paymentCycle || 0
          }]
        }
      }
    } else if (res.data.proportionReceivedPaymentAmount || res.data.paymentCycle) {
      // 如果没有详细数据但有原字段数据，转换为列表
      deliveryPaymentList.value = [{
        ratio: res.data.proportionReceivedPaymentAmount || 0,
        cycle: res.data.paymentCycle || 0
      }]
    }
    
    // 处理安装验收款信息数据回显
    if (res.data.installationPaymentDetail) {
      try {
        const installationData = JSON.parse(res.data.installationPaymentDetail)
        if (Array.isArray(installationData) && installationData.length > 0) {
          installationPaymentList.value = installationData
        }
      } catch (e) {
        // 如果解析失败，使用原有字段数据
        if (res.data.installationAcceptancePaymentRatio || res.data.paymentCycle2) {
          installationPaymentList.value = [{
            ratio: res.data.installationAcceptancePaymentRatio || 0,
            cycle: res.data.paymentCycle2 || 0
          }]
        }
      }
    } else if (res.data.installationAcceptancePaymentRatio || res.data.paymentCycle2) {
      // 如果没有详细数据但有原字段数据，转换为列表
      installationPaymentList.value = [{
        ratio: res.data.installationAcceptancePaymentRatio || 0,
        cycle: res.data.paymentCycle2 || 0
      }]
    }
    
    // 触发一次计算以同步数据
    calculatePaymentRatios()
    
  } catch (error) {
    console.error('获取预算单详情失败', error)
    ElMessage.error('获取预算单详情失败')
  }
}

// 实时预算预览数据
const previewData = reactive<{ grossMargin?: number; totalWeight?: number }>({})

// 防抖函数，避免频繁请求
const fetchPreview = debounce(async () => {
  if (!form.projectId) {
    previewData.grossMargin = undefined
    previewData.totalWeight = undefined
    return
  }
  try {
    const res = await getBudgetSheetDetailPreviewApi({ 
      ...form, 
      id: id.value || undefined,
      otherExpenses: totalOtherExpenses.value,
      otherExpensesDetail: JSON.stringify(otherExpensesList.value)
    })
    // 只取需要的字段
    previewData.grossMargin = res.data?.grossMargin
    previewData.totalWeight = res.data?.totalWeight
    // 如需展示更多字段，可在此扩展
  } catch (e) {
    previewData.grossMargin = undefined
    previewData.totalWeight = undefined
  }
}, 400)

// 监听基本信息相关字段变化
watch(
  () => [
    form.projectId,
    form.targetAmount,
    form.saleType,
    form.integratedPlanningType,
    form.orderType,
    form.orderType2,
    form.warrantyPeriodYear,
    form.otherExpenses,
    // ...如有其他影响毛利率的字段可补充
  ],
  fetchPreview,
  { immediate: true }
)

// 监听其他费用列表变化
watch(
  () => otherExpensesList.value,
  () => {
    calculateTotalOtherExpenses()
  },
  { deep: true, immediate: true }
)

// 监听付款比例相关字段变化，自动计算预付款比例
watch(
  () => [
    totalDeliveryPaymentRatio.value,
    totalInstallationPaymentRatio.value,
    form.warrantyMoney
  ],
  () => {
    calculatePrepaymentRatio()
  },
  { immediate: true }
)

// 监听到货款列表变化
watch(
  () => deliveryPaymentList.value,
  () => {
    calculatePaymentRatios()
  },
  { deep: true, immediate: true }
)

// 监听安装验收款列表变化
watch(
  () => installationPaymentList.value,
  () => {
    calculatePaymentRatios()
  },
  { deep: true, immediate: true }
)

// 表单提交时带上毛利率
const submitForm = async () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      // 自定义验证付款信息
      const hasValidDeliveryPayment = deliveryPaymentList.value.some(item => item.ratio > 0 || item.cycle > 0)
      const hasValidInstallationPayment = installationPaymentList.value.some(item => item.ratio > 0 || item.cycle > 0)
      
      if (!hasValidDeliveryPayment) {
        ElMessage.warning('请至少填写一条到货款信息')
        return
      }
      
      if (!hasValidInstallationPayment) {
        ElMessage.warning('请至少填写一条安装验收款信息')
        return
      }
      submitLoading.value = true
      const submitAction = async () => {
        try {
          // 提交前将毛利率写入form
          if (previewData.grossMargin !== undefined) {
            form.grossMargin = previewData.grossMargin
          }
          
                      // 准备提交数据，包含各种详情
            const submitData = {
              ...form,
              otherExpenses: totalOtherExpenses.value, // 其他费用总金额
              otherExpensesDetail: JSON.stringify(otherExpensesList.value), // 其他费用详细信息
              // 付款信息汇总
              proportionReceivedPaymentAmount: totalDeliveryPaymentRatio.value, // 到货款比例合计
              paymentCycle: calculateTotalCycle(deliveryPaymentList.value), // 到货款付款周期总和
              installationAcceptancePaymentRatio: totalInstallationPaymentRatio.value, // 安装验收款比例合计
              paymentCycle2: calculateTotalCycle(installationPaymentList.value), // 安装验收款付款周期总和
              // 付款信息详情（用于回显）
              deliveryPaymentDetail: JSON.stringify(deliveryPaymentList.value),
              installationPaymentDetail: JSON.stringify(installationPaymentList.value)
            }
          
          if (id.value) {
            // 编辑模式
            const updateData = {
              id: id.value,
              projectId: form.projectId || 0,
              ...submitData
            } as BudgetSheetUpdateDTO
            await updateBudgetSheetApi(updateData)
            ElMessage.success('更新预算单成功')
          } else {
            // 新增模式
            const createData = {
              projectId: form.projectId || 0,
              ...submitData
            } as BudgetSheetCreateDTO
            await addBudgetSheetApi(createData)
            ElMessage.success('新增预算单成功')
          }
          goBack()
        } catch (error: any) {
          console.error('提交预算单失败', error)
          // 如果后端返回了具体的错误信息，优先显示
          const errorMessage = error?.response?.data?.message || error?.message || '提交失败，请检查数据后重试'
          ElMessage.error(errorMessage)
        } finally {
          submitLoading.value = false
        }
      }
      submitAction()
    } else {
      ElMessage.warning('请完善表单信息')
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push({ path: '/budgetSheet' })
}

// 预览预算单
const handlePreviewBudgetSheet = async () => {
  // 验证必填字段
  if (!form.projectId) {
    ElMessage.warning('请先选择项目后再预览')
    return
  }

  // 显示加载状态
  ElMessage({
    message: '正在生成预览数据...',
    type: 'info',
    duration: 1000
  })

  // 1. 先确保字典数据已加载
  if (warrantyPeriodYearOptions.value.length === 0) {
    await getWarrantyPeriodYearOptions()
  }

  // 2. 再请求预览数据
  const previewData = {
    ...form,
    // 如果是编辑模式，包含ID
    id: id.value || undefined,
    // 包含其他费用详细信息
    otherExpenses: totalOtherExpenses.value,
    otherExpensesDetail: JSON.stringify(otherExpensesList.value),
    // 包含付款信息汇总
    proportionReceivedPaymentAmount: totalDeliveryPaymentRatio.value,
    paymentCycle: calculateTotalCycle(deliveryPaymentList.value),
    installationAcceptancePaymentRatio: totalInstallationPaymentRatio.value,
    paymentCycle2: calculateTotalCycle(installationPaymentList.value),
    // 包含付款信息详细信息
    deliveryPaymentDetail: JSON.stringify(deliveryPaymentList.value),
    installationPaymentDetail: JSON.stringify(installationPaymentList.value)
  }

  getBudgetSheetDetailPreviewApi(previewData).then(res => {
    // @ts-ignore - 后端返回的数据结构可能与TypeScript定义不完全一致
    currentBudgetSheet.value = res.data
    budgetDialog.visible = true
    budgetDialog.title = '预算单预览'
  }).catch(error => {
    console.error('获取预算单预览失败', error)
    ElMessage.error('获取预算单预览失败，请检查数据后重试')
  })
}

const budgetPreviewRef = ref<InstanceType<typeof BudgetSheetPreview> | null>(null)

// 打印预算单
const printBudgetSheet = () => {
  const printWindow = window.open('', 'PRINT', 'height=800,width=1200')
  if (printWindow) {
    // 获取预览组件的DOM元素
    const previewElement = document.querySelector('.budget-content')
    if (!previewElement) {
      ElMessage.error('获取预算单内容失败')
      return
    }
    
    const printContents = previewElement.innerHTML
    
    // 直接使用打印内容
    printWindow.document.write(`
      <html>
        <head>
          <title>预算单</title>
          <base href="${window.location.origin}${window.location.pathname}">
          <style>
            body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
            table { width: 99%; border-collapse: collapse; margin: 0 auto; }
            table, th, td { border: 1px solid black; }
            th, td { padding: 5px; text-align: center; vertical-align: middle; }
            .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; text-align: center; }
            .title { font-size: 18px; font-weight: bold; text-align: center; }
            .date { text-align: center; }
            .yellow-bg { background-color: #FFFF00; }
            .yellow-bg td { text-align: center; vertical-align: middle; }
            .pink-bg { background-color: #FFCCCC; }
            .blue-bg { background-color: #CCFFFF; }
            .total-row { font-weight: bold; }
            .print-button { display: none !important; }
            .budget-header { 
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 24px;
              padding-bottom: 16px;
              border-bottom: 1px solid #ebeef5;
              position: relative;
              text-align: center;
            }
            .budget-logo {
              position: absolute;
              top: 10px;
              text-align: center;
            }
            .budget-logo img.logo-image {
              max-width: 150px;
              height: auto;
              margin: 0 auto;
            }
            .budget-info {
              text-align: center;
              margin: 0 auto;
              width: 100%;
            }
            .budget-info h2 {
              margin: 0;
              font-size: 24px;
              color: #303133;
              text-align: center;
            }
            .budget-date {
              text-align: center;
              font-size: 14px;
              color: #606266;
            }
            .budget-table {
              width: 99%;
              border-collapse: collapse;
              margin: 16px auto;
            }
            .budget-table td {
              text-align: center;
              vertical-align: middle;
              padding: 8px;
              border: 1px solid #000;
            }
            .budget-footer {
              margin-top: 24px;
              padding-top: 16px;
              border-top: 1px solid #ebeef5;
              display: flex;
              justify-content: center;
              align-items: center;
              text-align: center;
            }
            .total-row td {
              font-weight: bold;
              background-color: #f2f2f2;
              text-align: center;
              vertical-align: middle;
            }
          </style>
        </head>
        <body>
          ${printContents}
        </body>
      </html>
    `)
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    printWindow.close()
    budgetDialog.visible = false
  } else {
    ElMessage.error('无法打开打印窗口，请检查浏览器设置')
  }
}

// 关闭预算单弹窗
const handleCloseBudgetDialog = () => {
  budgetDialog.visible = false
}

// 保存预算单到历史记录
const saveBudgetSheet = () => {
  if (!currentBudgetSheet.value || !currentBudgetSheet.value.id) {
    ElMessage.warning('未获取到预算单数据，无法保存')
    return
  }
  
  // 获取预览组件的DOM元素
  const previewElement = document.querySelector('.budget-content')
  if (!previewElement) {
    ElMessage.error('获取预算单内容失败')
    return
  }
  
  // 构建完整的HTML内容，包含样式
  const styleContent = `
    <style>
      body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
      table { width: 99%; border-collapse: collapse; margin: 0 auto; }
      table, th, td { border: 1px solid black; }
      th, td { padding: 5px; text-align: center; vertical-align: middle; }
      .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; text-align: center; }
      .title { font-size: 18px; font-weight: bold; text-align: center; }
      .date { text-align: center; }
      .yellow-bg { background-color: #FFFF00; }
      .yellow-bg td { text-align: center; vertical-align: middle; }
      .pink-bg { background-color: #FFCCCC; }
      .blue-bg { background-color: #CCFFFF; }
      .total-row { font-weight: bold; }
      .print-button { display: none !important; }
      .budget-header { 
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #ebeef5;
        position: relative;
        text-align: center;
      }
      .budget-logo {
        position: absolute;
        top: 10px;
        text-align: center;
      }
      .budget-logo img.logo-image {
        max-width: 150px;
        height: auto;
        margin: 0 auto;
      }
      .budget-info {
        text-align: center;
        margin: 0 auto;
        width: 100%;
      }
      .budget-info h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
        text-align: center;
      }
      .budget-date {
        text-align: center;
        font-size: 14px;
        color: #606266;
      }
      .budget-table {
        width: 99%;
        border-collapse: collapse;
        margin: 16px auto;
      }
      .budget-table td {
        text-align: center;
        vertical-align: middle;
        padding: 8px;
        border: 1px solid #000;
      }
      .budget-footer {
        margin-top: 24px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
      }
      .total-row td {
        font-weight: bold;
        background-color: #f2f2f2;
        text-align: center;
        vertical-align: middle;
      }
    </style>
  `
  
  // 获取内容并移除打印按钮
  let htmlContent = previewElement.innerHTML
  // 将打印按钮部分替换为空
  htmlContent = htmlContent.replace(/<div class="budget-footer">[\s\S]*?<\/div>/g, '')
  
  // 完整的HTML文档
  const fullContent = `
    <div class="budget-content">
      ${htmlContent}
    </div>
    ${styleContent}
  `
  
  // 构建保存数据
  const saveData = {
    budgetSheetId: currentBudgetSheet.value.id,
    projectId: currentBudgetSheet.value.projectId || 0,
    content: fullContent
  }
  
  // 调用保存API
  saveHistoricalBudgetSheetApi(saveData)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success('预算单保存成功')
        handleCloseBudgetDialog()
      } else {
        ElMessage.error(res.msg || '保存预算单失败')
      }
    })
    .catch((err) => {
      console.error('保存预算单失败', err)
      ElMessage.error('保存预算单失败')
    })
}

onMounted(async () => {
  await getProjectOptions()
  await getCustomerOptions()
  await getPersonOptions()
  await getSaleTypeOptions()
  await getPlanningTypeOptions()
  await getOrderTypeOptions()
  await getOrderType2Options()
  await getMarketingExpensesOptions()
  await getWarrantyPeriodYearOptions()
  await getUrgentFeeTipOptions()
  if (id.value) {
    await getBudgetSheetDetail()
  }
})
</script>

<style scoped lang="scss">
.budget-sheet-form {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  .box-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 18px;
        font-weight: 600;
      }
      
      .buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .base-info-card,
  .fee-info-card,
  .payment-info-card {
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    
    .form-section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #409eff;
    }
  }
}

.full-width {
  width: 100%;
}

/* 其他费用组件样式 */
.other-expenses-container {
  width: 100%;
  
  .other-expense-item {
    margin-bottom: 12px;
    padding: 12px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background-color: #fafbfc;
    
    &:hover {
      border-color: #c0c4cc;
    }
  }
  
  .other-expenses-total {
    margin-top: 16px;
    padding: 12px;
    background-color: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 6px;
    text-align: center;
    font-weight: 600;
    color: #409eff;
  }
}

/* 付款信息组件样式 */
.payment-info-container {
  width: 100%;
  
  .payment-info-header {
    margin-bottom: 12px;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    
    .column-header {
      font-weight: 600;
      color: #606266;
      font-size: 14px;
    }
  }
  
  .payment-info-item {
    margin-bottom: 12px;
    padding: 12px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background-color: #fafbfc;
    
    &:hover {
      border-color: #c0c4cc;
    }
  }
  
  .payment-info-total {
    margin-top: 16px;
    padding: 12px;
    background-color: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 6px;
    text-align: center;
    font-weight: 600;
    color: #409eff;
  }
}

/* 预算单弹窗样式 */
.budget-content {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;

  .budget-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;

    .budget-logo {
      position: absolute;
      top: 10px;
      text-align: center;

      .logo-image {
        max-width: 150px;
        height: auto;
        margin: 0 auto;
      }
    }

    .budget-info {
      text-align: center;
      margin: 0 auto;
      width: 100%;

      h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
        text-align: center;
      }
    }

    .budget-date {
      text-align: center;
      font-size: 14px;
      color: #606266;
    }
  }

  .budget-table {
    width: 99%;
    border-collapse: collapse;
    margin: 16px auto;
    
    td {
      padding: 8px;
      border: 1px solid #000;
      text-align: center;
      vertical-align: middle;
    }
    
    .yellow-bg {
      background-color: #FFFF00;
      
      td {
        text-align: center;
        vertical-align: middle;
        font-weight: normal;
      }
    }
    
    .pink-bg {
      background-color: #FFCCCC;
    }
    
    .blue-bg {
      background-color: #CCFFFF;
    }
    
    .total-row td {
      font-weight: bold;
      background-color: #f2f2f2;
    }
  }

  .budget-footer {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
  }
}

@media print {
  body {
    width: 100%;
    margin: 0;
    padding: 0;
  }

  .budget-content {
    padding: 0;
    box-shadow: none;
  }

  .budget-table {
    font-size: 12px;
    
    td {
      padding: 5px;
    }
  }

  .budget-footer {
    display: none !important;
  }
  
  .print-button {
    display: none !important;
  }
}
</style> 